package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 自媒体用户登录
     * @param wmUserDTO
     * @return
     */
    @Override
    public ResponseResult login(WmUserDTO wmUserDTO) {
        if(StringUtils.isBlank(wmUserDTO.getName()) || StringUtils.isBlank(wmUserDTO.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //根据用户名 查询 用户
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, wmUserDTO.getName()));
        if(wmUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //获取盐  将用户输入的密码 加盐 加密后进行比对
        String salt = wmUser.getSalt();
        String md5Pwd = DigestUtils.md5DigestAsHex((wmUserDTO.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
        if(!md5Pwd.equals(wmUser.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //验证账户 状态是否正常
        if (wmUser.getStatus() != 9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //有效就更改用户登录时间
        wmUser.setLoginTime(new Date());
        updateById(wmUser);
        //颁发token
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        //响应前端
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);

        //封装map
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",wmUserVO);

        return ResponseResult.okResult(map);
    }
}
